package jsave.process;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jsave.conf.Configuration;
import jsave.conf.Options;
import jsave.exception.JSaveFichierNonExistantException;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.PropertyConfigurator;

/** @deprecated */
public class FindDiffProcess extends JSaveProcess {

	private long lastSave;

	private List<String> diff;

	/** @deprecated */
	public FindDiffProcess(Configuration conf) {
		super(conf);
	}

	@Override
	public void execute() {

		try {
			lastSave = getLastSaveInMillis();
		} catch (Exception e) {
			log.info("Pas derniere date de sauvegarde trouve");
			return;
		}

		fileFilterS = conf.getFileFilterSource();
		diff = new ArrayList<String>();
		diff.add("last_save_in_millis=" + System.currentTimeMillis());
		ecartDateFichierCopie = Options.getInstance()
				.getEcartDateFichierCopie();

		findDiff(conf.getSource());
		afficherDiff();
		genererDiffFile();
	}

	private void findDiff(File rep) {

		File[] ts = rep.listFiles(fileFilterS);
		File f;

		// Affichage du dossier parcouru
		// Console.logParcours(rep.getPath());

		for (int i = 0; i < ts.length; i++) {
			f = ts[i];
			if (f.isDirectory()) {
				nbDossiersParcourus++;
				if ((f.lastModified() + ecartDateFichierCopie) > lastSave) {
					log.debug("R " + f.lastModified() + ">" + lastSave);
					diff.add(f.getPath().replace(
							conf.getSource().getPath() + File.separator, "D="));
				} else {
					findDiff(f);
				}
			} else {
				nbFichiersParcourus++;
				if ((f.lastModified() + ecartDateFichierCopie) > lastSave) {
					log.debug("F " + f.lastModified() + ">" + lastSave);
					diff.add(f.getPath().replace(
							conf.getSource().getPath() + File.separator, "F="));
				}
			}
		}
	}

	private void genererDiffFile() {
		if (diff.size() == 1) {
			log.info("Aucune differences trouvees");
		} else {
			File f = new File(conf.getSource().getPath() + File.separator
					+ ".jsavediff");
			try {
				f.createNewFile();
				FileUtils.writeLines(f, diff);
			} catch (IOException e) {
				log.error("Impossible de generer le fichier de diff " + f, e);
			}
		}
	}

	private void afficherDiff() {
		for (int i = 0; i < diff.size(); i++) {
			log.info(diff.get(i));
		}
	}

	public static void main(String[] args)
			throws JSaveFichierNonExistantException {
		PropertyConfigurator
				.configure(Options.getInstance().getInstallPath()
						+ File.separator + "conf" + File.separator
						+ "log4j.properties");
		Configuration c = new Configuration();
		// c.setSource("E:/data/perso/test1");
		c.setSource("E:/");
		new FindDiffProcess(c).execute();
	}
}
